package com.caiyi.financial.nirvana.sms.service;

import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsRegisterUser;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsRegisterUserStatusEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserChargeTypeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserTypeEnum;
import com.caiyi.financial.nirvana.sms.mapper.SmsRegisterUserMapper;
import com.caiyi.financial.nirvana.sms.querybean.PageBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryUserBean;
import com.youyu.common.api.Result;
import com.github.pagehelper.PageHelper;
import com.youyu.common.enums.BaseResultCode;
import com.youyu.common.utils.YyAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SmsRegisterUserService extends BaseService<SmsRegisterUser> {


    private static final String LOGIN_ACCOUNT = "login";

    @Autowired
    private SmsRegisterUserMapper smsRegisterUserMapper;

    @Autowired
    private SmsUserService userService;

    public PageBean<SmsRegisterUser> selectRegisterUserList(QueryUserBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsRegisterUser> list = smsRegisterUserMapper.selectRegisterUserList(bean);
        PageBean<SmsRegisterUser> pageBean = new PageBean<>(list);
        return pageBean;
    }

    /**
     * 开通用户
     *
     * @param id
     * @return
     */
    @Transactional
    public void openAccount(Integer id) {
        int count = smsRegisterUserMapper.updateStatus(SmsRegisterUserStatusEnum.ALREADY_OPENED.index, id);
        if (count > 0) {
            SmsRegisterUser smsRegisterUser = smsRegisterUserMapper.getRegisterUser(id);
            int extendCode = userService.getMaxExtendCode();
            YyAssert.isFalse(extendCode == 0, ReturnCodeEnum.FAILED.code, "最大扩展码有误");
            SmsUser smsUser = new SmsUser();
            smsUser.setAccount(smsRegisterUser.getPhone());
            smsUser.setType(SmsUserTypeEnum.INDUSTRY.index);
            smsUser.setChargeType(SmsUserChargeTypeEnum.BEFORE.index);
            smsUser.setExtendCode(extendCode + 1 + "");
            smsUser.setCompanyName(smsRegisterUser.getCompanyName());
            smsUser.setName(smsRegisterUser.getName());
            userService.addUser(smsUser);
        }
    }

    public void reject(Integer id, String remark) {
        smsRegisterUserMapper.reject(SmsRegisterUserStatusEnum.REJECT.index, id, remark);
        logger.info("reject success id : {} ", id);
    }

}
